package com.persistence;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.Query;

import com.domain.Location;

public class LocationAccessObject extends DataAccessObject<Location>{
	private String appUser;
	
	public void setAppUser(String appUser){
		this.appUser = appUser;
	}
	
	public void deleteLocation(String locationName){
		getPersistenceManagerInstance();
		Location deletingLocation = getLocation(locationName);
		persistenceManager.deletePersistent(deletingLocation);
		closePersistenceManager();
	}
	
	@Override
	public ArrayList<Location> getObjects() {
		// TODO Auto-generated method stub
		getPersistenceManagerInstance();
		ArrayList<Location> locationList = getLocationList();
		closePersistenceManager();
		return locationList;
	}

	@Override
	public Location getObject(String searchValue) {
		// TODO Auto-generated method stub
		getPersistenceManagerInstance();
		Location loc = getLocation(searchValue);
		closePersistenceManager();
		return loc;
	}

	public void updateObject(String originalValue,String locationName, double locationRadius){
		getPersistenceManagerInstance();
		Location loc = getLocation(originalValue);
		loc.setLocationName(locationName);
		loc.setErrorRadius(locationRadius);
		closePersistenceManager();
	}
	
	@SuppressWarnings("unchecked")
	private Location getLocation(String searchValue){
		Query query = persistenceManager.newQuery(Location.class);
		query.setFilter("locationName == locationNameParam");
		query.declareParameters("String locationNameParam");
		List<Location> location = (List<Location>)query.execute(searchValue);
		Location searchedLoc = null;
		if(location.size() > 0){
			searchedLoc = location.get(0);
		}
		return searchedLoc;
	}
	
	@SuppressWarnings("unchecked")
	private ArrayList<Location> getLocationList(){
		ArrayList<Location> locationList = new ArrayList<Location>();
		Query query = persistenceManager.newQuery(Location.class);
		query.setFilter("userName == appUserParam");
		query.declareParameters("String appUserParam");
		List<Location> list = (List<Location>)query.execute(appUser);
		for(Location loc : list){
			locationList.add(loc);
		}
		return locationList;
	}
}
